<script>
import {getGroupList, createUser} from '@/api/user'
import {searchGlobalSettings} from '@/api/globalSetting'
import md5 from 'js-md5'

function newForm() {
  return {
    id: 0,
    name: '',
    telephone: '',
    email: '',
    group_id: 1
  }
}

function checkPhone(rule, value, callback) {
  const reg = /^\d{11}$/
  if (!reg.test(value)) {
    callback(new Error(this.$t('user_phone_rule')))
  } else {
    callback()
  }
}

export default {
  name: 'UserCreatePage',
  data() {
    return {
      groupList: [],
      form: {
        name: '',
        telephone: '',
        email: '',
        password: '',
        group_id: 3,
        groupName: '',
        avatarIndex: 0
      },
      avatarList: [
      require('@/assets/avatars/1.jpg'),
        require('@/assets/avatars/2.jpg'),
        require('@/assets/avatars/3.jpg'),
        require('@/assets/avatars/4.jpg'),
        require('@/assets/avatars/5.jpg'),
        require('@/assets/avatars/6.jpg'),
        require('@/assets/avatars/7.jpg'),
        require('@/assets/avatars/8.jpg'),
        require('@/assets/avatars/9.jpg'),
        require('@/assets/avatars/10.jpg'),
        require('@/assets/avatars/11.jpg'),
        require('@/assets/avatars/12.jpg'),
        require('@/assets/avatars/13.jpg'),
        require('@/assets/avatars/14.jpg'),
        require('@/assets/avatars/15.jpg'),
        require('@/assets/avatars/16.jpg'),
        require('@/assets/avatars/17.jpg'),
        require('@/assets/avatars/18.jpg'),
        require('@/assets/avatars/19.jpg'),
        require('@/assets/avatars/20.jpg'),
      ],
      rules: {
        name: [
          { required: true, message: '请输入用户名称', trigger: 'blur' }
        ],
        // password: [
        //   { required: false, message: '请输入密码', trigger: 'blur' }
        // ],
        telephone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { min: 11, max: 11, message: this.$t('user_phone_rule'), trigger: 'blur' },
          { type: 'number', validator: checkPhone, message: '请填写正确手机号', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        group_id: [
          { required: true, message: '请选择用户组', trigger: 'blur' }
        ]
      },
    };
  },
  computed: {
    // 计算属性过滤掉 id=1 的用户组（管理员）
    filteredGroupList() {
      return this.groupList.filter(g => g.id !== 1);
    }
  },
  created() {
    // 获取默认密码
    this.password = 'telestar'
    // 加载组列表数据
    getGroupList().then(response => {
      this.groupList = response.data
    })
  },
  methods: {
    getGroupName(group_id) {
      for (var i = 0; i < this.groupList.length; i++) {
        if (group_id === this.groupList[i].id) {
          return this.groupList[i].name
        }
      }
    },
    selectAvatar(index) {
      this.form.avatarIndex = index;
    },
    cancelCreate() {
      this.$router.push({ path: '/configuration/user' })
    },
    onCreate() {
      // 如果密码为空，则默认为 "telestar"
      if (this.form.password === '') {
        this.form.password = 'telestar';
      }
      console.log(this.form);
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          this.$message({
            type: 'warning',
            message: '请检查输入内容是否符合要求'
          })
          return
        } else {
          // md5加密
          this.form.password = md5(this.form.password)
          createUser(this.form).then((response) => {
            if (response.code == 200) {
              this.$message({
                type: 'success',
                message: '添加成功'
              });
              this.$router.push({ path: '/configuration/user' })
            } else {
              if (response.message === 'telephone already exist') {
                this.$message({
                  type: 'error',
                  message: '手机号已存在'
                });
              } else if (response.message === 'email already exist') {
                this.$message({
                  type: 'error',
                  message: '邮箱已存在'
                });
              } else {
                this.$message({
                  type: 'error',
                  message: '添加失败'
                });
              }
            }
          }).catch((error) => {
            console.error('Error creating user:', error);
            this.$message({
              type: 'error',
              message: '系统错误，请稍后再试'
            });
          });
        }
      });
    }
  }
}
</script>

<template>
  <div class="create-user-page">
    <div class="create-container">
      <el-form ref="form" :model="form" :rules="rules" inline-message="true">
        <el-form-item :label="$t('user') + $t('group')" label-width="120px" prop="group_id" >
          <el-select v-model="form.group_id" style="width: 250px;">
            <el-option v-for="(g, index) in filteredGroupList" :key="index" :label="g.name" :value="g.id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('nickname')" label-width="120px" prop="name">
          <el-input v-model="form.name" autocomplete="off" style="width: 250px;"/>
        </el-form-item>
        <!-- <el-form-item :label="$t('password')" label-width="120px" prop="password">
          <el-input v-model="form.password" autocomplete="off" style="width: 250px;"/>
        </el-form-item> -->
        <el-form-item :label="$t('telephone')" label-width="120px" prop="telephone">
          <el-input v-model="form.telephone" autocomplete="off" style="width: 250px;"/>
        </el-form-item>
        <el-form-item :label="$t('email')" label-width="120px" prop="email">
          <el-input v-model="form.email" autocomplete="off" style="width: 250px;"/>
        </el-form-item>
        <el-form-item :label="$t('avatar')" label-width="120px">
          <!-- 显示当前选中的头像 -->
          <el-image :src="avatarList[form.avatarIndex]" fit="cover" style="width: 100px; height: 100px;"></el-image>
          <!-- 使用 div 来展示头像列表 -->
          <div class="avatar-grid" v-if="avatarList.length > 0">
            <el-image
              v-for="(avatarUrl, index) in avatarList"
              :key="index"
              :src="avatarUrl"
              fit="cover"
              style="width: 50px; height: 50px;"
              @click="selectAvatar(index)"
            ></el-image>
          </div>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <!-- <el-button @click="cancelCreate">{{ $t('cancel') }}</el-button> -->
        <el-button type="primary" @click="onCreate">{{ $t('confirm') }}</el-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.create-user-page {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
.dialog-footer {
  text-align: left;
  margin-left: 120px;
  margin-top: 20px;
}
.avatar-grid {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
  gap: 30px; /* 间距 */
}

.create-container {
  width: 100%;
  max-width: 1000px;
  padding: 20px;
  border-left: 1px solid #DCDFE6;
  border-radius: 4px !important;
  background-color: #fff;
}
</style>
